package com.jkkc.lib.base.widget

import android.content.Context
import android.util.AttributeSet
import android.view.KeyEvent
import androidx.appcompat.widget.AppCompatEditText
import com.blankj.utilcode.util.LogUtils
import com.jkkc.lib.base.extend.BOOLEAN_TRUE
import com.jkkc.lib.base.util.WriterLocalUtils

/**
 * Author:LiXian
 * <p>
 * Desc:支持扫码的EditText，解决扫码枪与中文输入法冲突的问题
 * Version:1.0
 * date 2023/4/7 15:00
 */
class ScannerEditText @JvmOverloads constructor(mContext: Context, attrs: AttributeSet? = null, defStyleAttr: Int = android.R.attr.editTextStyle)
    : AppCompatEditText(mContext, attrs, defStyleAttr) {

    private var mResult: String = ""
    private var mCallback: ((String) -> Unit)? = null

    fun setCallback(callback: (String) -> Unit) {
        mCallback = callback
    }

    override fun dispatchKeyEventPreIme(event: KeyEvent?): Boolean {
        if (event == null) {
            return super.dispatchKeyEventPreIme(event)
        }
        if (0 == event.unicodeChar) {
            LogUtils.d("扫码或外部虚拟键盘输入，unicodeChar == 0，不处理")
            return true
        }

        if (event.action == KeyEvent.ACTION_DOWN) {
            mResult += event.unicodeChar.toChar()
            LogUtils.d("扫码或外部虚拟键盘输入，内容拼接mResult = $mResult")
        }
        if (event.device.name.contains("my_key", BOOLEAN_TRUE)
                || event.device.name.contains("matrix_keypad", BOOLEAN_TRUE)) {
            mResult = ""
            LogUtils.d("虚拟按键，不拦截本次输入内容，清空记录内容 mResult = $mResult")
            return false
        }
        // 默认使用KEYCODE_ENTER作为结束标志
        if (event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER) {
            mResult = mResult.trim()
            WriterLocalUtils.writeOperation(log = "扫码结果回调mResult = $mResult", BOOLEAN_TRUE)
            mCallback?.invoke(mResult)
            mResult = ""
        }
        return true
    }
}